package com.ruoyi.common.client;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;

@Slf4j
@Component
public class HSClient {
    @Value("${huashu.ip}")
    public String hsIp;

    public Map<String, String> getHeaderMap(String token) {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("application", "x-www-form-urlencoded");
        headerMap.put("Authorization",token);
        return headerMap;
    }

    /**
     * POST请求
     */
    public R postRequstObj(String url, Object params, Class clazz,String token) {
        String json = JSON.toJSONString(params);
        log.info("请求地址：{}, 参数：{}", url, json);
        HttpResponse execute = HttpUtil.createPost(hsIp+url).headerMap(this.getHeaderMap(token), false).setConnectionTimeout(500).body(json).execute();
        R baseResponse = HttpResponseUtil(execute, clazz);
        return baseResponse;
    }

    /**
     * POST请求 带请求参数
     */
    public R postRequstParm(String url, Object params, Class clazz,String token) {
        String json = JSON.toJSONString(params);
        log.info("请求地址：{}, 参数：{}", url, json);
        HttpResponse execute = HttpUtil.createPost(hsIp+url+"?id="+json).headerMap(this.getHeaderMap(token), false).setConnectionTimeout(500).execute();
        R baseResponse = HttpResponseUtil(execute, clazz);
        return baseResponse;
    }

    /**
     * POST请求
     */
    public R postRequestBody(String url, Map<String, Object> params, Class clazz) {
        String json = JSON.toJSONString(params);
        log.info("请求地址：{}, 参数：{}", url, json);
        HttpResponse execute = HttpUtil.createPost(url).headerMap(this.getHeaderMap(url), false).setConnectionTimeout(500).body(json).execute();
        R baseResponse = HttpResponseUtil(execute, clazz);
        return baseResponse;
    }



    /**
     * PUT请求
     */
    public R putRequst(String url, Map<String, Object> requestParam, Class clazz) {
        log.info("请求地址：{}, 参数：{}", url, JSON.toJSONString(requestParam));
        HttpResponse execute = HttpUtil.createRequest(Method.PUT, url).headerMap(this.getHeaderMap(url), false).setConnectionTimeout(500).body(JSON.toJSONString(requestParam)).execute();
        R baseResponse = HttpResponseUtil(execute, clazz);
        return baseResponse;
    }

    /**
     * PUT请求
     */
    public R putRequstObj(String url, Object object, Class clazz) {
        String json = JSON.toJSONString(object);
        log.info("请求地址：{}, 参数：{}", url, json);
        HttpResponse execute = HttpUtil.createRequest(Method.PUT, url).headerMap(this.getHeaderMap(url), false).setConnectionTimeout(500).body(json).execute();
        R baseResponse = HttpResponseUtil(execute, clazz);
        return baseResponse;
    }

    /**
     * 删除请求
     */
    public R deleteRequst(String url, Map<String, Object> requestParam, Class clazz) {
        log.info("请求地址：{}, 参数：{}", url, JSON.toJSONString(requestParam));
        HttpResponse execute = HttpUtil.createRequest(Method.DELETE, url).headerMap(this.getHeaderMap(url), false).setConnectionTimeout(500).body(JSON.toJSONString(requestParam)).execute();
        return HttpResponseUtil(execute, clazz);
    }

    /**
     * 删除请求
     * 不带参数
     */
    public R deleteRequstNoParam(String url, Class clazz) {
        log.info("请求地址：{}, ", url);
        Map<String, String> headerMap = this.getHeaderMap(url);
        headerMap.put("Content-Type", "application/json");
        HttpResponse execute = HttpUtil.createRequest(Method.DELETE, url).headerMap(headerMap, false).setConnectionTimeout(500).execute();
        return HttpResponseUtil(execute, clazz);
    }

    /**
     * GET请求
     */
    public R getRequest(String url, Class clazz,String token) {
        log.info("请求地址：{}", url);
        HttpResponse execute = HttpUtil.createGet(hsIp+url).headerMap(this.getHeaderMap(token), false).setConnectionTimeout(500).execute();
        return HttpResponseUtil(execute, clazz);
    }
    /**
     * GET请求
     */
    public R getRequest(String url,Object param, Class clazz,String token) {
        String json = JSON.toJSONString(param);
        log.info("请求地址：{},{}", url,json);
        HttpResponse execute = HttpUtil.createGet(hsIp+url+"?"+param).headerMap(this.getHeaderMap(token), false).setConnectionTimeout(500).execute();
        return HttpResponseUtil(execute, clazz);
    }

    /**
     * 解析返回值
     */
    public static R HttpResponseUtil(HttpResponse execute, Class clazz) {
        if (execute.isOk()) {
            String body = execute.body();
            JSONObject bodyO = JSONObject.parseObject(body);
            if (!Objects.equals(bodyO.get("code"),200)){
                throw new RuntimeException("华数接口异常=="+bodyO.get("message"));
            }
            Object result = bodyO.get("result");
            String jsonString = JSON.toJSONString(result);
            boolean validArray = JSON.isValidArray(jsonString);
            log.debug("返回参数{}", jsonString);
            if (validArray){
                return  R.ok(JSON.parseArray(jsonString,clazz));
            }else {
                return R.ok(JSON.parseObject(jsonString, clazz));
            }
        } else {
            StringBuilder message = new StringBuilder();
            try {
                log.info("请求接口失败，状态码：{}，返回内容：{}", execute.getStatus(), execute.body());
                JSONObject jsonObject = JSON.parseObject(execute.body());
                jsonObject.keySet().forEach(key -> {
                    message.append(jsonObject.getJSONObject(key).getString("message"));
                });
            } catch (Exception e) {
                throw new RuntimeException("华数接口异常"+message);
            }
        }
        throw new RuntimeException("华数接口异常");
    }

}
